package com.im323.ip.impl;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.im323.common.util.HttpClientUtils;
import com.im323.common.util.IpModel;
import com.im323.common.util.IpUtil;
import com.im323.common.util.JsonUtil;
import com.im323.ip.IpConverter;

public class IpTBConvert extends IpConverter {

	@Override
	public IpModel parse() {
		long sta = System.currentTimeMillis();
		String doGet = HttpClientUtils.doGet(IpUtil.URL_TB);

		IpModel ipModel = null;
		try {
			JsonNode rootNode = JsonUtil.getMapper().readTree(doGet);

			if (rootNode != null) {
				JsonNode dataNodex = rootNode.get("data");
				if (dataNodex != null) {
					JsonNode countryNode = dataNodex.get("country");
					JsonNode cityNode = dataNodex.get("city");
					JsonNode ipNode = dataNodex.get("ip");
					JsonNode ispNode = dataNodex.get("isp");

					ipModel = new IpModel();
					ipModel.setIpAddress(ipNode.textValue());
					ipModel.setIsp(ispNode.textValue());
					ipModel.setLocation(countryNode.textValue() + " " + cityNode.textValue());
					ipModel.setDelay(System.currentTimeMillis() - sta);
					ipModel.setUrl(IpUtil.URL_TB);
				}
			}
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ipModel;
	}

}
